local LevelSchema = {}

json = gJson
template_level_len = 0

local template_level = [[
{
	"randomSeed": {* param.randomSeed *},
	"moveLimit": {* param.moveLimit *},
	"specialTileThreshold": {* param.specialTileThreshold *},
	"orderList": {* tostring(json.encode(param.orderList)) *},
	"difficulty": {* param.difficulty *},
	"numberOfColours": {* param.numberOfColours *},
	"defaultColor": {* tostring(json.encode(param.defaultColor)) *},
	"windmill": {* tostring(json.encode(param.windmill)) *},
	"crystalEditData": {* tostring(json.encode(param.crystalEditData)) *},
	"dropRules": [
		{% for k,vline in ipairs(param.dropRules) do %}		{* tostring(json.encode(vline)) *}{* NeedFlags(not(k==#param.dropRules), ",") *}
		{% end %}	],
	"titleMap":	[
		{% for i,vline in ipairs(param.tileMap) do %}
		[{% for k,val in ipairs(vline) do %}{* json.encode(val) *}{* GapFill(val, k==#vline, template_level_len) *}{% end %}]{* NeedFlags(not(i==#param.tileMap), ",") *}
		{% end %}	],
	"specialAnimalMap": [
		{% for k,vline in ipairs(param.specialAnimalMap) do %}		{* tostring(json.encode(vline)) *}{* NeedFlags(not(k==#param.specialAnimalMap), ",") *}
		{% end %}	],
	"seaAnimalMap": [
		{% for k,vline in ipairs(param.seaAnimalMap) do %}		{* tostring(json.encode(vline)) *}{* NeedFlags(not(k==#param.seaAnimalMap), ",") *}
		{% end %}	],
	"gameModeName": {* tostring(json.encode(param.gameModeName)) *}
}]]

function LevelSchema.Render(cfg, json)
	function CalcMaxLen(cfg)
		local ret = 0
		for _, vline in ipairs(cfg.tileMap) do
			for _, val in ipairs(vline) do
				local content_len = string.len(json.encode(val))
				if content_len > ret then
					ret = content_len
				end
			end
		end
		return ret
	end

	template_level_len = CalcMaxLen(cfg)

	function GapFill(val, lastone, max_len)
		local ret = ""
		if lastone then return ret end

		local len = string.len(json.encode(val))
		if len == 0 then return ret end

		ret = ret ..","
		if len >= max_len then return ret end
		for i=1, max_len-len do
			ret = ret .." "
		end
		return ret
	end

	function NeedFlags(bFlag, flag)
		if bFlag then return flag end
		return ""
	end

	-- Using template.render
	local template = require "service.TemplateEngine.lib.resty.template"
	return template.process(template_level, { param = cfg, max_len = max_len})
end

return LevelSchema